package 行为型模式

import java.util.*


/**
 * 允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类
 */
sealed interface State {
    fun init(): String
    fun reply(input: String): String
}

object DisconnectedState : State {
    override fun init(): String {
        return "Bye!"
    }

    override fun reply(input: String): String {
        return ""
    }
}

object ConnectedState : State {
    override fun init(): String {
        return "Hello, I'm Bob."
    }

    override fun reply(input: String): String {
        if (input.endsWith("?")) {
            return "Yes. " + input.substring(0, input.length - 1) + "!";
        }
        if (input.endsWith(".")) {
            return input.substring(0, input.length - 1) + "!";
        }
        return input.substring(0, input.length - 1) + "?";
    }

}


class BotContext {
    private var state: State = DisconnectedState
    fun chat(input: String): String {
        if ("hello" == input) {
            // 收到hello切换到在线状态:
            state = ConnectedState
            return state.init()
        } else if ("bye" == input) {
            // 收到bye切换到离线状态:
            state = DisconnectedState
            return state.init()
        }
        return state.reply(input)
    }
}

fun main() {
    val scanner = Scanner(System.`in`)
    val bot = BotContext()
    while (true) {
        print("> ")
        val input: String = scanner.nextLine()
        val output: String = bot.chat(input)
        println(if (output.isEmpty()) "(no reply)" else "< $output")
    }
}